package langyu

import (
	"context"
	"crypto/md5"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"time"

	"github.com/rs/zerolog/log"
)

type Client struct {
	account string
	pwd     string
}

var ErrInteralError = errors.New("短信发送服务异常")

func NewClient(account, pwd string) Client {
	return Client{account: account, pwd: pwd}
}

func (c Client) Send(ctx context.Context, mobile, txt string) error {
	param := make(url.Values)
	ts := time.Now().Local().Format("20060102150405")
	param["account"] = []string{c.account}
	param["ts"] = []string{ts}
	param["pswd"] = []string{fmt.Sprintf("%x", md5.Sum([]byte(c.account+c.pwd+ts)))}
	param["mobile"] = []string{mobile}
	param["msg"] = []string{txt}

	res, err := http.PostForm("https://i.lyxxjs.com/msg/HttpBatchSendSM", param)
	if err != nil {
		log.Error().Err(err).Msg("xinlian code send err")
		return ErrInteralError
	}
	defer res.Body.Close()

	// d, _ := ioutil.ReadAll(res.Body)
	// fmt.Printf("resp body:%s", string(d))

	// decoder := json.NewDecoder(res.Body)
	// var r Response
	// if err = decoder.Decode(&r); err != nil {
	// 	log.Error().Err(err).Msg("xinlian code send response resolve err")
	// 	return ErrInteralError
	// }
	// if r.Code != 0 {
	// 	return errors.New(r.Msg)
	// }

	return nil
}
